package com.thti.mecool.client.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.thti.mecool.client.base.BaseActivity;
import com.thti.mecool.client.base.HandlerConstant;
import com.thti.mecool.client.model.biz.TaskManageBizImpl;
import com.thti.mecool.client.model.biz.TaskStepBizImpl;
import com.thti.mecool.client.model.po.TaskManage;
import com.thti.mecool.client.model.po.TaskStep;
import com.thti.mecool.client.service.LocateService;
import com.thti.mecool.client.util.Util;
import com.thti.mecool.client.widget.AlterDialogWidget;
import com.thti.mecool.client.widget.IsOKListener;
import com.thti.mecool.client.widget.Toolbar;

public class MultipleChoice extends BaseActivity{
	private ListView mecool_mulaction_list;
	private int[] actionIds;
	String curStepId;
	private String[] taskItemName;
	private int[] curActionIds;
	private String action_title = null;
	@SuppressWarnings("unused")
	private Toolbar toolbar;
	private String taskDatatypeName;
	private String planId, projectId, parentId, taskId, parentStepId;
	private String[] StepIds;
	@SuppressWarnings("unused")
	private TaskManageBizImpl taskManageBizImpl;
	private TaskManage taskManage;
	private ArrayList<Integer> isOvers;
	private ArrayList<String> parentIds;
	private HashMap<String, Integer> finishStat;
	private RelativeLayout relativeLayout;
	private String curParentId;
	private ImageButton save, cancel;
	private String stepId;
	private SharedPreferences load;
	@SuppressWarnings("unused")
	private String taskName;
	private TextView action_text;
@Override
protected void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	setContentView(R.layout.mecool_multiple_choice_layout);
	load = getSharedPreferences("LocationService", 0);
	Intent in = new Intent(this, LocateService.class);
	in.putExtra("flag", 101);
	startService(in);
	Intent i=getIntent();
	planId=i.getStringExtra("planId");
	projectId=i.getStringExtra("projectId");
	taskId=i.getStringExtra("taskId");
	parentId=i.getStringExtra("parentId");
	parentStepId=i.getStringExtra("parentStepId");
	mecool_mulaction_list=(ListView)findViewById(R.id.mecool_mulaction_list);
	finishStat = new HashMap<String, Integer>();
	isOvers = new ArrayList<Integer>();
	parentIds = new ArrayList<String>();
	action_text = (TextView) findViewById(R.id.mecool_mulaction_text);

	toolbar = new Toolbar(this);
	Toolbar.hideRightButton();
	Toolbar.left_btn.setImageResource(R.drawable.mecool_go_back);
	Toolbar.left_btn.setOnClickListener(onClickListener);
	save = (ImageButton) findViewById(R.id.mecool_task_mulaction_save);
	cancel = (ImageButton) findViewById(R.id.mecool_task_mulaction_cancel);
	save.setOnClickListener(onClickListener);
	cancel.setOnClickListener(onClickListener);
	relativeLayout = (RelativeLayout) findViewById(R.id.mecool_task_mulaction_btn);
	getTaskforSQL(parentId);
	for(int a=0;a<actionIds.length;a++){
		if(actionIds[a]==-1){
			actionIds[a]=5;
		}
	}
	mecool_mulaction_list.setAdapter(adapter);
	mecool_mulaction_list.setOnItemClickListener(onItemClickListener);
}
private OnClickListener onClickListener = new OnClickListener() {
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.mecool_toolbar_leftbtn:
			finish();
			break;
		case R.id.mecool_task_mulaction_save:
			Util.sendToast(MultipleChoice.this, "保存已经成功！");
			isFinish(1);
			finish();
			break;
		case R.id.mecool_task_mulaction_cancel:
			new AlertDialog.Builder(MultipleChoice.this)
					.setTitle("提示").setMessage("已完成的步骤将被清空，确认要退出吗？")
					.setNegativeButton("取消", dialogClickListener)
					.setPositiveButton("确认", dialogClickListener).create()
					.show();
			break;
		default:
			break;
		}
	}
};

private android.content.DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {

	@Override
	public void onClick(DialogInterface dialog, int which) {
		switch (which) {
		case -1:
			TaskStepBizImpl taskStepBizImpl = new TaskStepBizImpl(
					MultipleChoice.this);
			List<Map<String, Object[]>> list = new ArrayList<Map<String, Object[]>>();
			for (int i = 0; i < StepIds.length; i++) {
				Map<String, Object[]> map = new HashMap<String, Object[]>();
				String[] ids = new String[] { "0", planId, projectId,
						StepIds[i], taskId };
				map.put(HandlerConstant.PLAN_UPDATE_SQL, ids);
				String[] ids2 = new String[] { null, planId, projectId,
						StepIds[i], taskId };
				map.put(HandlerConstant.TASK_STEP_UPDATE_DATA_SQL, ids2);
				list.add(map);
			}
			taskStepBizImpl.updateStep(list);
			isFinish(0);
			finish();
			break;
		default:
			break;
		}
	}
};

private void getTaskforSQL(String parentId) {
	try{
	isOvers.clear();
	parentIds.clear();
	finishStat.clear();
	TaskStepBizImpl taskStepBizImpl = new TaskStepBizImpl(this);
	List<TaskStep> tasks = taskStepBizImpl.findByStep(planId, projectId,
			parentId,taskId);
	System.out.println(tasks.size());
	StepIds = new String[tasks.size()];
	taskItemName = new String[tasks.size()];
	actionIds = new int[tasks.size()];
	for (int i = 0; i < tasks.size(); i++) {
		isOvers.add(tasks.get(i).getIsOver());
		if (tasks.get(i).getActionId() == 4) {
			action_title += " - " + tasks.get(i).getName();
			getTaskforSQL(tasks.get(i).getStepId());
		}
		actionIds[i] = tasks.get(i).getActionId();
		taskItemName[i] = tasks.get(i).getName();
		StepIds[i] = tasks.get(i).getStepId();
		if(tasks.get(i).getIsFinsh()==1)
		finishStat.put(tasks.get(i).getStepId(), tasks.get(i).getIsFinsh());
		else
		finishStat.remove(tasks.get(i).getStepId())	;
		parentIds.add(tasks.get(i).getParentId());
	}
	}catch(Exception e){
		Util.sendToast(this, "步骤配置错误");
		finish();
		e.printStackTrace();
	}
}

private void getMulTaskforSQL(String parentId) {
	try{
	TaskStepBizImpl taskStepBizImpl = new TaskStepBizImpl(this);
	List<TaskStep> tasks = taskStepBizImpl.findByStep(planId, projectId,
			parentId,taskId);
	if(tasks.size()==0){
		if(taskStepBizImpl==null)
		taskStepBizImpl = new TaskStepBizImpl(
				MultipleChoice.this);
		List<Map<String, Object[]>> list = new ArrayList<Map<String, Object[]>>();
		if(!finishStat.containsKey(stepId)){
			Map<String, Object[]> map = new HashMap<String, Object[]>();
			String[] ids = new String[] { String.valueOf(1), planId,
					projectId, stepId, taskId };
			map.put(HandlerConstant.PLAN_UPDATE_SQL, ids);
			Map<String, Object[]> map2 = new HashMap<String, Object[]>();
			String[] ids2 = new String[] { String.valueOf(1), planId,
					projectId, parentStepId, taskId };
			map2.put(HandlerConstant.PLAN_UPDATE_SQL, ids2);
			list.add(map2);
			taskStepBizImpl.updateStep(list);	
		}
//		else{
//			Map<String, Object[]> map = new HashMap<String, Object[]>();
//			String[] ids = new String[] { String.valueOf(0), planId,
//					projectId, stepId, taskId };
//			map.put(HandlerConstant.PLAN_UPDATE_SQL, ids);
//			Map<String, Object[]> map2 = new HashMap<String, Object[]>();
//			String[] ids2 = new String[] { String.valueOf(0), planId,
//					projectId, parentStepId, taskId };
//			map2.put(HandlerConstant.PLAN_UPDATE_SQL, ids2);
//			list.add(map2);
//			taskStepBizImpl.updateStep(list);
//		}
		finish();
		}

	isOvers.clear();
	parentIds.clear();
	finishStat.clear();
	StepIds = new String[tasks.size()];
	taskItemName = new String[tasks.size()];
	actionIds = new int[tasks.size()];
	for (int i = 0; i < tasks.size(); i++) {
		isOvers.add(tasks.get(i).getIsOver());
		actionIds[i] = tasks.get(i).getActionId();
		taskItemName[i] = tasks.get(i).getName();
		StepIds[i] = tasks.get(i).getStepId();
		if(tasks.get(i).getIsFinsh()==1)
		finishStat.put(tasks.get(i).getStepId(), tasks.get(i).getIsFinsh());
		else
		finishStat.remove(tasks.get(i).getStepId())	;
		parentIds.add(tasks.get(i).getParentId());
	}
	}catch(Exception e){
		Util.sendToast(this, "步骤配置错误");
		finish();
		e.printStackTrace();
	}
}

private OnItemClickListener onItemClickListener=new OnItemClickListener() {
	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		stepId=StepIds[arg2];
		parentId=parentIds.get(arg2);
		switch (actionIds[arg2]) {
		case 5:
			curStepId=StepIds[arg2];
			getMulTaskforSQL(StepIds[arg2]);
			adapter.notifyDataSetChanged();
			break;
		case 4:
			TaskStepBizImpl taskStepBizImpl=new TaskStepBizImpl(MultipleChoice.this);
			taskStepBizImpl.clearStep(planId, taskId, StepIds[arg2], projectId);
			List<Map<String,Object[]>> list=new ArrayList<Map<String,Object[]>>();
			Map<String,Object[]> arg=new HashMap<String,Object[]>();
			//isFinsh=? where planId=? and projectId=?  and stepId=? and taskId=?";
			arg.put(HandlerConstant.PLAN_UPDATE_SQL, new String[]{"0",planId,projectId,StepIds[arg2],taskId});
			arg.put(HandlerConstant.TASK_STEP_UPDATE_DATA_SQL, new String[]{null,planId,projectId,StepIds[arg2],taskId});
			list.add(arg);
			taskStepBizImpl.updateStep(list);
			Intent intent=new Intent(MultipleChoice.this,TaskStepActionActivity.class);
			intent.putExtra(taskName, taskItemName[arg2]);
			intent.putExtra("planId", planId);
			intent.putExtra("projectId", projectId);
			intent.putExtra("taskId", taskId);
			intent.putExtra("parentStepId", parentStepId);
			intent.putExtra("parentId", StepIds[arg2]);
			intent.putExtra("text_name", taskItemName[arg2]);
			intent.putExtra("isMulChoice", true);
			startActivity(intent);
			break;
		case 2:
			AlterDialogWidget ad = new AlterDialogWidget(
					MultipleChoice.this);
			ad.setEditTextDialog();
			ad.setReturnView(arg1.findViewWithTag("tv2"));
			ad.setIsOKListener(isOKListener);
			ad.show();
			break;
		case 3:
			AlterDialogWidget ad2 = new AlterDialogWidget(
					MultipleChoice.this);
			ad2.setEditTextDialog();
			ad2.setReturnView(arg1.findViewWithTag("tv2"));
			ad2.setIsOKListener(isOKListener);
			ad2.show();
			break;
		}
	}
};

private IsOKListener isOKListener = new IsOKListener() {
	@Override
	public void isOk(boolean isPutOk, String content) {
		if (isPutOk) {
			complete(content);
			relativeLayout.setVisibility(0);
		}
	}
};
public void isFinish(int finish) {
	TaskStepBizImpl taskStepBizImpl = new TaskStepBizImpl(
			MultipleChoice.this);
	List<Map<String, Object[]>> list = new ArrayList<Map<String, Object[]>>();
	Map<String, Object[]> map = new HashMap<String, Object[]>();
	String[] ids = new String[] { String.valueOf(finish), planId,
			projectId, parentStepId, taskId };
	map.put(HandlerConstant.PLAN_UPDATE_SQL, ids);
	list.add(map);
	taskStepBizImpl.updateStep(list);
}

private void complete(String content) {
	taskManage=new TaskManage();
	taskManage.setIsType(2);
	taskManage.setPlanId(planId);
	taskManage.setProjectId(projectId);
	taskManage.setTaskId(taskId);
	taskManage.setStepId(stepId);
	taskManage.setIsUpload(0);
	taskManage.setData(content);
	taskManage.setLatitude(load.getString("Latitude", null));
	taskManage.setLongitude(load.getString("Longitude", null));
	TaskStepBizImpl taskStepBizImpl = new TaskStepBizImpl(this);
	List<Map<String, Object[]>> list = new ArrayList<Map<String, Object[]>>();
	Map<String, Object[]> map = new HashMap<String, Object[]>();
	String[] ids = new String[] { "1", planId, projectId, stepId, taskId };
	map.put(HandlerConstant.PLAN_UPDATE_SQL, ids);
	list.add(map);
	taskStepBizImpl.updateStep(list);
	taskStepBizImpl.updateData(taskManage);
	adapter.notifyDataSetChanged();
}

@Override
protected void onResume() {
	super.onResume();
	if(adapter!=null){
		adapter.notifyDataSetChanged();}
};
private BaseAdapter adapter=new BaseAdapter() {
	
	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		convertView = getLayoutInflater().inflate(
				R.layout.mecool_task_action_step_item, null);
		TextView tv = (TextView) convertView
				.findViewById(R.id.mecool_task_action_step_item_title);
		TextView tv2 = (TextView) convertView
				.findViewById(R.id.mecool_task_action_step_item_content);
		ImageView iv = (ImageView) convertView
				.findViewById(R.id.mecool_task_action_step_item_imageview);
	tv.setText(taskItemName[position]);
	TaskStepBizImpl taskStepBizImpl=new TaskStepBizImpl(MultipleChoice.this);
	String data=taskStepBizImpl.findStepData(planId, projectId, taskId, parentIds.get(position),StepIds[position]);
	if(data!=null){
		tv2.setText(data);
		tv2.setVisibility(0);
	}else{
		tv2.setVisibility(8);
	}
	tv2.setTag("tv2");
		if (finishStat.containsKey(StepIds[position])&&finishStat.get(StepIds[position])==1) {
			iv.setVisibility(0);
			isFinish(1);
		} else {
			iv.setVisibility(8);
		}
		return convertView;
	}
	
	@Override
	public long getItemId(int position) {
		return position;
	}
	
	@Override
	public Object getItem(int position) {
		return taskItemName[position];
	}
	
	@Override
	public int getCount() {
		return taskItemName.length;
	}
};
}
